import type { Test } from "@server/src/schemas/tests";
import type { ColumnDef, FilterFn } from "@tanstack/react-table";
import { CircleCheckIcon, CircleXIcon } from "lucide-react";

const ownerFilterFn: FilterFn<Test> = (row, filterValue) => {
  if (!filterValue) return true;
  const ownerValue = row.original.extra?.owner;
  if (!ownerValue) return false;
  return Array.isArray(filterValue) ? filterValue.includes(ownerValue) : ownerValue === filterValue;
};

const TestTitle = ({ status, title }: { status: string; title: string }) => {
  if (status === "passed") {
    return (
      <div className="flex items-center justify-start gap-2">
        <CircleCheckIcon className="size-4" />
        <p>{title}</p>
      </div>
    );
  } else {
    return (
      <div className="flex items-center justify-start gap-2 text-destructive">
        <CircleXIcon className="size-4" />
        <p>{title}</p>
      </div>
    );
  }
};

const inArray: FilterFn<Test> = (row, id, filterValue) => {
  if (!filterValue || !Array.isArray(filterValue)) return true;
  return filterValue.includes(row.getValue<string>(id));
};

export const TestsColumns: ColumnDef<Test>[] = [
  {
    accessorKey: "status",
    header: "Status",
    filterFn: inArray,
  },
  {
    accessorKey: "name",
    header: "Name",
    cell: ({ row }) => TestTitle({ status: row.original.status, title: row.original.name }),
    size: 800,
  },
  {
    accessorKey: "issue",
    header: "Issue",
    size: 120,
  },
  {
    accessorKey: "owner",
    header: "Owner",
    cell: ({ row }) => row.original.extra.owner,
    size: 120,
    filterFn: ownerFilterFn,
  },
];
